<template>
  
  <el-popover placement="right" :width="225" trigger="hover">
      <template #reference>
        <div class="floating-square" :style="squareStyle">打赏</div>
      </template>
      <img src="../../assets/picture/moneyMa.jpg" style="width: 200px;height: 200px;">
    </el-popover>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 初始化小方块的位置和速度
const x = ref(0)
const y = ref(0)
const speedX = ref((Math.random() - 0.5) * 2)
const speedY = ref((Math.random() - 0.5) * 2)

const squareStyle = ref({
  transform: `translate(${x.value}px, ${y.value}px)`
})

// 获取容器的尺寸和位置
const containerRef = ref(null)
const containerWidth = ref(0)
const containerHeight = ref(0)
const offset = 5 // 偏移量

const updateContainerSize = () => {
  if (containerRef.value) {
    const rect = containerRef.value.getBoundingClientRect()
    containerWidth.value = window.innerWidth-50
    containerHeight.value = window.innerHeight
  }
}

// 更新位置的函数
const updatePosition = () => {
  x.value += speedX.value
  y.value += speedY.value

  // 检查边界条件并反弹
  if (x.value <= offset || x.value >= containerWidth.value - 50 - offset) {
    speedX.value = -(Math.random() - 0.5) * 2
  }
  if (y.value <= offset || y.value >= containerHeight.value - 50 - offset) {
    speedY.value = -(Math.random() - 0.5) * 2
  }

  squareStyle.value = {
    transform: `translate(${x.value}px, ${y.value}px)`
  }
}

// 启动动画
let animationFrameId
const startAnimation = () => {
  animationFrameId = requestAnimationFrame(() => {
    updatePosition()
    startAnimation()
  })
}

// 监听窗口大小变化
const handleResize = () => {
  updateContainerSize()
}

onMounted(() => {
  containerRef.value = document.querySelector('.container')
  updateContainerSize()
  startAnimation()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  cancelAnimationFrame(animationFrameId)
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.floating-square {
  width: 50px;
  height: 50px;
  background-color: #007bff;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.1s;
  cursor: pointer;
  border-radius: 8px;
  z-index: 9999;
}
</style>